var jWindow = $(window);
$(document).ready(function() {
	
	$(window).on("load",function(){
		imgLocation();
		var imgData ={"data":[{"src":"1.jpg"},{"src":"2.jpg"},{"src":"3.jpg"},{"src":"4.jpg"},{"src":"5.jpg"},{"src":"6.jpg"},{"src":"7.jpg"},{"src":"8.jpg"},
		                      {"src":"9.jpg"},{"src":"10.jpg"},{"src":"11.jpg"},{"src":"12.jpg"},{"src":"13.jpg"},{"src":"14.jpg"},{"src":"15.jpg"},{"src":"16.jpg"},
		                      {"src":"17.jpg"},{"src":"18.jpg"},{"src":"19.jpg"},{"src":"20.jpg"},{"src":"21.jpg"},{"src":"22.jpg"}]}
		
		window.onscroll = function () {
			var box = $(".box");
			var boxWidth = box.eq(0).width();
			var boxHeight = box.eq(0).height();
			var scrollHeight = jWindow.scrollTop();
			var contentHeight = $(document).height()-box.eq(0).height();
			console.log(scrollHeight);
			if(scrollHeight<=boxHeight){
				$(".content1").css({
					position:"absolute",
					left:"0px",
					top:scrollHeight-boxHeight +"px"
				});
			}
			if(scrollHeight>boxHeight && scrollHeight<contentHeight){
				$(".content1").css({
					position:"absolute",
					left:"0px",
					top:scrollHeight-boxHeight +200+"px"
				});
			}
			
			if(scrollside()){
				$.each(imgData.data,function(index,value){
					var box = $("<div>").addClass("box").appendTo($("#container"));
					var content = $("<div>").addClass("content").appendTo(box);
					console.log("./image/"+$(value).attr("src"));
					$("<img>").attr("src","./image/"+$(value).attr("src")).appendTo(content);
					});
				
				imgLocation();
			}
		};
	});
});

function scrollside() {
	var box = $(".box");
	var lastboxHeight = box.last().get(0).offsetTop+Math.floor(box.last().height()/2);
	var documentHeight = $(document).height();
	var scrollHeight = $(window).scrollTop();
	return (lastboxHeight<scrollHeight+documentHeight)?true:false;
}
function imgLocation() {//确定每个图片的安排位置
	var box = $(".box");
	var boxWidth = box.eq(0).width();
	var num = Math.floor(($(window).width()-150)/boxWidth);
	var boxArr =[];//每一个盒子的高度
	box.each(function(index,value){
		
		var boxHeight = box.eq(index).height();
		if(index <=num){
			boxArr[index] = boxHeight;
		}else{
			
			var minboxHeight = Math.min.apply(null,boxArr);//获取最小高度
			var minboxIndex = $.inArray(minboxHeight,boxArr);//获取最小高度的位置
			
			$(value).css({
				"position":"absolute",
				"top":minboxHeight,
				"left":box.eq(minboxIndex).position().left
			});
			boxArr[minboxIndex]+=box.eq(index).height();
		}
	});
}